package Tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class _515_FindLargestValueinEachTreeRow {
    //hint:use 2 queue,one holds present level's nodes and the other holds
    //sub level's nodes,when present level's queue empty,turn to the sub level's queue.
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        Queue<TreeNode> subQueue = new LinkedList<>();
        int max = Integer.MIN_VALUE;
        while (!queue.isEmpty()) {
            TreeNode temp = queue.poll();
            if (temp.val > max) {
                max = temp.val;
            }
            if (temp.left != null) {
                subQueue.add(temp.left);
            }
            if (temp.right != null) {
                subQueue.add(temp.right);
            }
            if (queue.isEmpty()) {
                res.add(max);
                max = Integer.MIN_VALUE;
                queue = subQueue;
                subQueue = new LinkedList<>();
            }
        }
        return res;
    }
}
